﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Forms;
using SCONFIG;

namespace SGUI
{
    public class LANG
    {
        public static void TextForm(Form x, string Lang)
        {
            Xmlconfig xcfg = new Xmlconfig(GetNameFile(Lang), true);

            if (xcfg.Settings[x.Name].Value == "" && xcfg.Settings[x.Name].ChildCount(true) == 0)
            {
                xcfg.Settings[x.Name].Value = x.Text;
                foreach (Control i in x.Controls)
                    dequy_xcfg(xcfg, i, x.Name + "/LANG");
                    
                xcfg.Save(GetNameFile(Lang));
            }
            x.Text = xcfg.Settings[x.Name].Value;
            if(xcfg.Settings[x.Name].ChildCount(true)==0)
                return;
            foreach(var i in xcfg.Settings[x.Name]["LANG"].Children())
            {
                Control[] tempC = x.Controls.Find(i.Name,true);
                if(tempC.Length>0)
                    tempC[0].Text = i.Value;
            }
        }

        static string GetNameFile(string Lang)
        {
            switch(Lang)
            {
                case "vi":
                    return "Lang/vietnamese.xml";
                case "en":
                    return "Lang/english.xml";
                default:
                    return "Lang/vietnamese.xml";
            }
        }

        public static void SaveTextForm(Form x, string Lang)
        {
            Xmlconfig xcfg = new Xmlconfig(GetNameFile(Lang), true);
            xcfg.Settings[x.Name].Value = x.Text;
            foreach(Control i in x.Controls)
                dequy_xcfg(xcfg, i, x.Name+"/LANG");
            xcfg.Save(GetNameFile(Lang));
        }

        static void dequy_xcfg(Xmlconfig xcfg, Control x, string pathname)
        {
            if (x.GetType() == typeof(DateTimePicker)) { return; }
            if (x.Text != "")
                xcfg.Settings[pathname + "/" + x.Name].Value = x.Text;
            foreach (Control i in x.Controls)
            {                
                if (i.Text != "")
                {
                    if (i.GetType() == typeof(DateTimePicker)) { continue; }
                    xcfg.Settings[pathname + "/" + i.Name].Value = i.Text;
                }                   
                if (i.Text == null || i.Text == "")
                    dequy_xcfg(xcfg, i, pathname);
            }
        }

        //private static string NormalizeDiacriticalCharacters(string value)
        //{
        //    if (value == null)
        //    {
        //        throw new ArgumentNullException("value");
        //    }

        //    var normalised = value.Normalize(NormalizationForm.FormD).ToCharArray();

        //    return new string(normalised.Where(c => (int)c <= 127).ToArray());
        //}
    }

}

